package com.ssy.lingxi.contract.esign;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.contract.esign.api.SignApi;
import com.ssy.lingxi.contract.esign.request.*;
import com.ssy.lingxi.contract.esign.response.*;
import com.ssy.lingxi.contract.esign.util.ApiUtil;

import java.io.File;
import java.io.FileInputStream;
import java.util.Collections;
import java.util.List;

public class SignDemo {

    SignApi signApi = null;

    /**
     * 个人账号创建
     */

    public void test1() throws Exception{
        PersonalAccountCreateRequest request = PersonalAccountCreateRequest.builder()
                .thirdPartyUserId("13250151295")
                .name("养殖场")
                .idType("CRED_PSN_CH_IDCARD")
                .idNumber("441322199610065215")
                .build();
        PersonalAccountCreateResponse response = signApi.account().personalAccountCreate(request);

        // {"accountId":"ca294255c8d14116b010cd94a8f2a6d6"}
        System.out.println(JSONUtil.toJsonStr(response));
    }

    /**
     * 机构账号创建
     */

    public void test2() throws Exception {

        OrgAccountCreateRequest request = OrgAccountCreateRequest.builder()
                .thirdPartyUserId("767427185@qq.com")
                .creator("ca294255c8d14116b010cd94a8f2a6d6")
                .name("滴滴打猪有限公司")
                .idType("CRED_ORG_UNKNOWN")
                .idNumber("441322199610065215")
                .build();

        OrgAccountCreateResponse response = signApi.account().orgAccountCreate(request);

        // {"accountId":"0725c98e768940a492e3df08a66bba5d"}
        System.out.println(JSONUtil.toJsonStr(response));
    }

    /**
     * 创建个人印章
     */

    public void test3() throws Exception {
        PersonalSealCreateRequest request = PersonalSealCreateRequest.builder()
                .accountId("ca294255c8d14116b010cd94a8f2a6d6")
                .alias("养殖场")
                .color("RED")
                .type("FZKC")
                .build();

        PersonalSealCreateResponse response = signApi.seal().personalSealCreate(request);

        // {"code":0,"message":"成功","data":{"sealId":"f65ff81c-3f1e-43a8-bd16-2c455693f4b3","fileKey":"$976655cc889540b9ad9c33b90a4baaf4$1901508800$H","url":"https://esignoss.esign.cn/seal-service/9eaef0ad-7097-45dc-bbcd-1bcecf23f6dd/3fba43a5-6b61-4f55-b528-1a37edb8e6e3-openseal.png?Expires=1598611303&OSSAccessKeyId=LTAIdvHfiVrzDKbE&Signature=u%2Br1whlmB4046VT4OULC1jqFBrU%3D","width":136,"height":136}}
        System.out.println(JSONUtil.toJsonStr(response));
    }

    /**
     * 上传方式创建文件
     */

    public void test4() throws Exception {
        File file = new File("D:/PDFTemplate.pdf");

        // md5处理
        FileInputStream fis = new FileInputStream(file);
        String md5Base64 = ApiUtil.fileMd5(fis);

        FileUploadCreateRequest request = FileUploadCreateRequest.builder()
                .contentMd5(md5Base64)
                .contentType("application/pdf")
                .convert2Pdf(false)
                .fileName(file.getName())
                .fileSize(file.length())
                .build();

        FileUploadCreateResponse response = signApi.fileTemplate().fileUploadCreate(request);

        // {"uploadUrl":"https://esignoss.esign.cn/1111564182/645424b2-31e0-4e28-baed-04d45940bb09/PDFTemplate.pdf?Expires=1598611369&OSSAccessKeyId=STS.NTnV6zCSF91PCyxFzMANZEM1z&Signature=Iat3T7xgyxEuG029Zy5jbzvfE%2F4%3D&callback-var=eyJ4OmZpbGVfa2V5IjoiJDgwMDcxMDE0OGI1ZjQyZGJhYTgzYThlNGU0NDY3ZjQ1JDI3MTk4MDkyNjMkSCJ9%0A&callback=eyJjYWxsYmFja1VybCI6Imh0dHA6Ly80Ny45OS4yMjQuMjM1OjgwODAvZmlsZS1zeXN0ZW0vY2FsbGJhY2svYWxpb3NzIiwiY2FsbGJhY2tCb2R5IjogIntcIm1pbWVUeXBlXCI6JHttaW1lVHlwZX0sXCJzaXplXCI6ICR7c2l6ZX0sXCJidWNrZXRcIjogJHtidWNrZXR9LFwib2JqZWN0XCI6ICR7b2JqZWN0fSxcImV0YWdcIjogJHtldGFnfSxcImZpbGVfa2V5XCI6JHt4OmZpbGVfa2V5fX0iLCJjYWxsYmFja0JvZHlUeXBlIjogImFwcGxpY2F0aW9uL2pzb24ifQ%3D%3D%0A&security-token=CAIS%2BAF1q6Ft5B2yfSjIr5fbHYzOroxnjvO7QV%2FJonoYTcF2qoiamDz2IHtKdXRvBu8Xs%2F4wnmxX7f4YlqB6T55OSAmcNZEoIRPoPajnMeT7oMWQweEurv%2FMQBqyaXPS2MvVfJ%2BOLrf0ceusbFbpjzJ6xaCAGxypQ12iN%2B%2Fm6%2FNgdc9FHHPPD1x8CcxROxFppeIDKHLVLozNCBPxhXfKB0ca0WgVy0EHsPnvm5DNs0uH1AKjkbRM9r6ceMb0M5NeW75kSMqw0eBMca7M7TVd8RAi9t0t1%2FIVpGiY4YDAWQYLv0rda7DOltFiMkpla7MmXqlft%2BhzcgeQY0pc%2FRqAATjLmQRcWBp6ETOnyaBOA2skALrWRl8HBxEtCU8dKaHc0iRtD0jBN6FKVYVv9w1ZbP5mjZ64xRFxqjFJUsuSKimmieYBN3C7tIJj8TQ05CtC8rgW%2FadDHFHtCJkcGl%2B2pvsd5Nt335n%2F8clsnMxsVNq5qMkJfG0KF%2Fi65iA0tq4y","fileId":"c1cacaf5e0fd48ec80495ca36763df9a"}
        System.out.println(JSONUtil.toJsonStr(response));


        // 上传文件
        String uploadUrlResultStr = HttpRequest.put(response.getUploadUrl())
                .header("Content-MD5", md5Base64)
                .header("Content-Type", "application/pdf")
                .body(IoUtil.readBytes(new FileInputStream(file)))
                .execute()
                .body();

        // {"errCode":0,"msg":"成功"}
        System.out.println(uploadUrlResultStr);
    }

    /**
     * 签署流程创建
     */

    public void test5() throws Exception {
        SignFlowCreateRequest request = new SignFlowCreateRequest();
        request.setBusinessScene("租房合同");

        SignFlowResponse response = signApi.signFlow().signFlowCreate(request);

        // {"flowId":"242b518dd67d4e378eaa9718f2e2d65c"}
        System.out.println(JSONUtil.toJsonStr(response));

    }

    /**
     * 流程文档添加
     */

    public void test6() throws Exception {
        SignFlowDocumentsAddRequest.Doc doc = new SignFlowDocumentsAddRequest.Doc();
        doc.setFileId("c1cacaf5e0fd48ec80495ca36763df9a");

        SignFlowDocumentsAddRequest request = SignFlowDocumentsAddRequest.builder()
                .flowId("242b518dd67d4e378eaa9718f2e2d65c")
                .docs(Collections.singletonList(doc))
                .build();

        signApi.signFlow().signFlowDocumentsAdd(request);
    }

    /**
     * 添加签署区
     */

    public void test7() throws Exception {
        String fileId = "c1cacaf5e0fd48ec80495ca36763df9a";
        WordsPositionSearchRequest searchRequest = WordsPositionSearchRequest.builder()
                .fileId(fileId)
                .keywords("甲方")
                .build();

        List<WordsPositionSearchResponse> searchResponsesList = signApi.helper().wordsPositionSearch(searchRequest);

        WordsPositionSearchResponse searchResponse = searchResponsesList.get(0);
        List<WordsPositionSearchResponse.Position> positionList = searchResponse.getPositionList();
        WordsPositionSearchResponse.Position position = positionList.get(0);
        List<WordsPositionSearchResponse.Position.Coordinate> coordinateList = position.getCoordinateList();
        WordsPositionSearchResponse.Position.Coordinate coordinate = coordinateList.get(0);


        SignFieldPlatformRequest.Signfield signfieldsBean = new SignFieldPlatformRequest.Signfield();
        signfieldsBean.setFileId(fileId);

        SignFieldPlatformRequest.Signfield.PosBean posBean = new SignFieldPlatformRequest.Signfield.PosBean();
        posBean.setPosPage(position.getPageIndex() + "");
        posBean.setPosX(coordinate.getPosx());
        posBean.setPosY(coordinate.getPosy());
        signfieldsBean.setPosBean(posBean);

        SignFieldPlatformRequest request = new SignFieldPlatformRequest();
        request .setFlowId("242b518dd67d4e378eaa9718f2e2d65c");
        request .setSignfields(Collections.singletonList(signfieldsBean));


        SignFieldPlatformResponse response = signApi.signFlow().signFieldPlatform(request);

        // {"signfieldBeans":[{"accountId":"bbd3ea11ef4d426b856348fb850613ff","signfieldId":"b4befe089a7e4d159e0d70af29370b3a","fileId":"c1cacaf5e0fd48ec80495ca36763df9a"}]}
        System.out.println(JSONUtil.toJsonStr(response));
    }

    /**
     * 签署流程开启
     */

    public void test8() throws Exception {
        String flowId = "242b518dd67d4e378eaa9718f2e2d65c";
        signApi.signFlow().signFlowStart(flowId);
    }

    /**
     * 签署流程归档
     */

    public void test9() throws Exception {
        String flowId = "242b518dd67d4e378eaa9718f2e2d65c";
        signApi.signFlow().signFlowArchive(flowId);
    }

    /**
     * 流程文档下载
     */

    public void test10() throws Exception {
        String flowId = "242b518dd67d4e378eaa9718f2e2d65c";
        SignFlowDocResponse response = signApi.signFlow().signFlowDocumentsDownload(flowId);

        // {"docs":[{"fileName":"PDFTemplate.pdf","fileUrl":"https://esignoss.esign.cn/1111563786/a4e10e23-34dc-4975-bfe3-beffe5756d1c/PDFTemplate.pdf?Expires=1598611751&OSSAccessKeyId=LTAIdvHfiVrzDKbE&Signature=TdllXyBI0uYsRlUkyJV1s8qRGxk%3D","fileId":"c1cacaf5e0fd48ec80495ca36763df9a"}]}
        System.out.println(JSONUtil.toJsonStr(response));
    }


    /**
     * 查询上传文件详情
     */

    public void getFileDetail() throws Exception {
        String fileId = "c1cacaf5e0fd48ec80495ca36763df9a";
        FileDetailResponse response = signApi.fileTemplate().fileDetail(fileId);
        System.out.println(JSONUtil.toJsonStr(response));
    }

    /**
     * 签署流程查询
     */

    public void signflowsDetail() throws Exception {
        String flowId = "242b518dd67d4e378eaa9718f2e2d65c";
        SignFlowDetailResponse response = signApi.signFlow().signFlowDetail(flowId);
        System.out.println(JSONUtil.toJsonStr(response));
    }
}
